Telegram Group & Telegram Channel
#повседневное

Вчерашний запрос, "заморозивший" миграцию на три часа:

SELECT entity_id, MAX(start_date), MAX(end_date)
FROM (
  SELECT entity_id, MAX(start_date) start_date, NULL AS end_date FROM audit_log
  WHERE attr = 'reviewed' AND newValue = 'true'
  GROUP BY entity_id
   UNION ALL
  SELECT entity_id, NULL AS start_date, MAX(end_date) end_date FROM audit_log
  WHERE attr = 'overriden' AND newValue = 'true'
  GROUP BY entity_id
) a GROUP BY entity_id; 

можно было бы написать сильно оптимальнее вот так:

SELECT entity_id, 
  MAX(if(attr = 'reviewed', NULL, start_date)) AS start_date,
    MAX(if(attr = 'reviewed', end_date, NULL)) end_date 
FROM audit_log
WHERE (attr = 'reviewed' OR attr='overriden') AND newValue = 'true'
GROUP BY entity_id;

При сильно похожих WHERE в таких конструкциях, удобнее схлопнуть UNION и "на лету" подставлять в SELECT нужное значение через if.



tg-me.com/developers_mind/57
Create:
Last Update:

#повседневное

Вчерашний запрос, "заморозивший" миграцию на три часа:

SELECT entity_id, MAX(start_date), MAX(end_date)
FROM (
  SELECT entity_id, MAX(start_date) start_date, NULL AS end_date FROM audit_log
  WHERE attr = 'reviewed' AND newValue = 'true'
  GROUP BY entity_id
   UNION ALL
  SELECT entity_id, NULL AS start_date, MAX(end_date) end_date FROM audit_log
  WHERE attr = 'overriden' AND newValue = 'true'
  GROUP BY entity_id
) a GROUP BY entity_id; 

можно было бы написать сильно оптимальнее вот так:

SELECT entity_id, 
  MAX(if(attr = 'reviewed', NULL, start_date)) AS start_date,
    MAX(if(attr = 'reviewed', end_date, NULL)) end_date 
FROM audit_log
WHERE (attr = 'reviewed' OR attr='overriden') AND newValue = 'true'
GROUP BY entity_id;

При сильно похожих WHERE в таких конструкциях, удобнее схлопнуть UNION и "на лету" подставлять в SELECT нужное значение через if.

BY Developer's mind


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/developers_mind/57

View MORE
Open in Telegram


Developer& 39;s mind Telegram | DID YOU KNOW?

Date: |

For some time, Mr. Durov and a few dozen staffers had no fixed headquarters, but rather traveled the world, setting up shop in one city after another, he told the Journal in 2016. The company now has its operational base in Dubai, though it says it doesn’t keep servers there.Mr. Durov maintains a yearslong friendship from his VK days with actor and tech investor Jared Leto, with whom he shares an ascetic lifestyle that eschews meat and alcohol.

Developer& 39;s mind from us


Telegram Developer's mind
FROM USA